class Solution {


    /**
     * 在一个排序数组中查找元素的第一个和最后一个位置 第34题
     * 时间复杂度O(logN)
     * @param nums
     * @param target
     * @return
     */

    public int[] searchRange(int[] nums, int target) {
        int[] list = { -1 , -1 };
        if(nums.length == 0){
            return list;
        }
        //  找区间的左端点
        int left = 0, right = nums.length - 1;
        while (left < right){
            int mid = left + (right - left) / 2;
            if(nums[mid] >= target){
                right = mid;
            }else {
                left = mid + 1;
            }
        }
        if(nums[left] == target){
            list[0] = left;
        }else {
            return list;
        }
        //  找区间的右端点
        right = nums.length - 1;
        while (left < right){
            int mid = left + (right - left + 1) / 2;
            if(nums[mid] <= target){
                left = mid;
            }else {
                right = mid - 1;
            }
        }
        list[1] = left;
        return list;
    }


    /**
     * 二分查找 704题
     * 时间复杂度O(logN)
     * @param nums 原数组
     * @param target 目标值
     * @return
     */
    public int search(int[] nums, int target) {
        return searchChild(nums,target);
    }

    public int searchChild(int[] nums, int target){
        int right = nums.length - 1, left = 0;
        while (left <= right){
            int mid = left + (right - left ) / 2; // 防止溢出
            if(nums[mid] > target){
                right = mid - 1;
            }else if(nums[mid] < target) {
                left = mid + 1;
            }else {
                return mid;
            }
        }
        return -1;
    }

}